package com.howie.hmvc.paramparse;

import java.lang.annotation.Annotation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.howie.hmvc.annotations.NoTrim;
import com.howie.hmvc.annotations.Valid;
import com.howie.hmvc.exception.ArguErrorException;

public class ParamStrings extends AbsParamParse{

	private boolean trim;
	private boolean isValid;
	private boolean required;
	private boolean email;
	private String regex;
	private double minLength;
	private double maxLength;
	
	@Override
	public void init(Annotation[] ans) throws Exception {
		Valid valid = getValid(ans);
		if(valid != null){
			isValid = true;
			required = valid.required();
			email = valid.email();
			regex = valid.regex();
			minLength = valid.minLength();
			maxLength = valid.maxLength();
		}
		trim = getNoTrim(ans) != null;
	}
	
	@Override
	public Object getParamter(HttpServletRequest request,HttpServletResponse response)throws Exception{
		String[] values = request.getParameterValues(name);
		if(values != null){
			for(int i=0;i<values.length;i++){
				if(isValid){
					if(StringUtils.isEmpty(values[i])){
						if(required){
							throw new ArguErrorException(name,"required",null);
						}
					}else{
						if(email && !values[i].matches("[\\w\\.\\-]+@([\\w\\-]+\\.)+[\\w\\-]+")){
							throw new ArguErrorException(name,"email",null);
						}
						if(values[i].length() < minLength){
							throw new ArguErrorException(name,"minLength",minLength);
						}
						if(values[i].length() > maxLength){
							throw new ArguErrorException(name,"maxLength",maxLength);
						}
						if(StringUtils.isNotEmpty(regex) && !values[i].matches(regex)){
							throw new ArguErrorException(name,"regex",null);
						}
					}
				}
				if(trim && values[i] != null){
					values[i] = values[i].trim();
				}
			}
		}
		return values;
	}
	
	/*
	 * 获取NoTrim注解
	 * @param an
	 * @return
	 */
	protected NoTrim getNoTrim(Annotation[] ans){
		for(Annotation a : ans){
			if(a instanceof NoTrim){
				return (NoTrim)a;
			}
		}
		return null;
	}
	
}
